package org.example.util;


import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.example.model.dto.UserDetailDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.*;

@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtUtils {

    private  String header;
    private  String tokenPrefix;
    private  String secret;
    private  long expireTime;


    public  void setHeader(String header) {
        this.header = header;
    }

    public  void setTokenPrefix(String tokenPrefix) {
        this.tokenPrefix = tokenPrefix;
    }


    public  void setSecret(String secret) {
        this.secret = secret;
    }

    public  void setExpireTime(long expireTime) {
        this.expireTime = expireTime;
    }


    /**
     * issuer 签发人
     * subject 一般存用户id
     * claims 一般存放用户角色权限信息
     * 创建token
     * @return
     */
    public String createToken(String issuer,String subject,
                                     Map<String,Object> claims){
        if(StringUtils.isEmpty(issuer)){
            issuer = "spring";
        }
        SecretKey secretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));
        String token = Jwts.builder().setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .signWith(secretKey,SignatureAlgorithm.HS256)
                .setIssuer(issuer)
                .setSubject(subject)
                .setIssuedAt(new Date())
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + expireTime * 1000))
                .compact();

        return token;
    }

    public Claims getClaims(String token){
        SecretKey secretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));
        Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        return body;
    }

    /**
     * 验证
     * @param token
     * @return
     */
//    public Boolean validateToken(String token){
//
//        try {
//
//            Claims claims = getClaims(token);
//            return (null!=claims && !isTokenExpired(token));
//
//        } catch (JwtException e) {
//
//            return false;
//        }
//    }

    public Boolean isTokenExpired(String token){
        Claims claims = getClaims(token);
        Date expiration = claims.getExpiration();
        return expiration.before(new Date());
    }




}
